const { VUE_APP_BASE_URL } = process.env;


export default <R>(options: RequestOptions) => new Promise<ResBody<R>>((resolve, reject) => {
  if (!options.hideLoading) {
    uni.showLoading({
      title: '加载中',
    });
  }
  const token = uni.getStorageSync('token') ? uni.getStorageSync('token') : '';
  const requestStr = JSON.stringify(options.data, null, 2);
  const requestOptions: UniApp.RequestOptions = {
    url: options.fullPath ? options.fullPath : (VUE_APP_BASE_URL as string + options.path),
    header: {
      'Content-Type': options.contentType || 'application/json',
      Authorization: token,
      appid: uni.getAccountInfoSync().miniProgram.appId,
      merchant: process.env.VUE_APP_MERCHANT,
      'L-A-Platform': 'mini-program', // 后端日志埋点渠道
    },
    method: options.method || 'get',
    data: options.data || '',
    success: (response: AnyObject) => {
      if (response.data.status === 200 ||
        response.data.code === 200 ||
        response.data.code === 0 ||
        response.data.code === 130007 || response.data.code === 1100) {
        resolve(response.data);
      } else {
        let message;
        if (typeof response.data.code !== 'undefined') {
          switch (response.data.code) {
            case 115004:
              message = '短信验证码不匹配';
              break;
            case 500:
              message = '网络开了小差，请重新尝试';
              break;
            default:
              message = response.data.message;
          }
        } else {
          message = response.data;
        }
        // 用户信息过期后重新授权,不提示，直接默认重新登录
        if (response.data.code === 9999) {
          // TODO 重登处理
        } else if (!options.hideErrModel) {
          uni.showModal({
            title: '温馨提示',
            content: message || '网络开了小差，请重新尝试',
            showCancel: false,
            confirmText: '确认',
            confirmColor: '#4694FA',
          });
        }
        reject(response.data);
      }
      if (!options.hideLoading) {
        uni.hideLoading();
      }
    },
    fail: (error) => {
      uni.showModal({
        title: '提醒',
        content: '网络开了小差，请重新尝试',
        showCancel: false,
        confirmText: '确认',
        confirmColor: '#4694FA',
      });
      reject(error);
      if (!options.hideLoading) {
        uni.hideLoading();
      }
    },
  };
  uni.request(requestOptions);
});
